package com.yan.deezer.ui.actionbar;

import android.content.Context;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;

import com.actionbarsherlock.view.ActionProvider;
import com.yan.deezer.R;
import com.yan.deezer.activity.DeezerDemoActivity;

public class SearchActionProvider extends ActionProvider {

	/** Context for accessing resources. */
	private final Context mContext;
	boolean x = false;

	/**
	 * Creates a new instance.
	 * 
	 * @param context
	 *            Context for accessing resources.
	 */

	public SearchActionProvider(Context context) {
		super(context);
		mContext = context;

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public View onCreateActionView() {

		// Inflate the action view to be shown on the action bar.
		final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
		final View view = layoutInflater.inflate(R.layout.search_box, null);

		final AutoCompleteTextView searchField = (AutoCompleteTextView) view
				.findViewById(R.id.search_field);
		// searchField.requestFocus();

		/*
		 * InputMethodManager imm =
		 * (InputMethodManager)mContext.getSystemService
		 * (Context.INPUT_METHOD_SERVICE); if (imm !=
		 * null&&searchField.hasFocus(
		 * )&&searchField.getVisibility()==View.VISIBLE){
		 * imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); }
		 */

		searchField.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					// Toast.makeText(mContext, searchField.getText(),
					// Toast.LENGTH_SHORT).show();

					DeezerDemoActivity.getDeezerFragmentInterface()
							.addArtistListFragmentToStack(
									searchField.getEditableText().toString());

					InputMethodManager imm = (InputMethodManager) mContext
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(searchField.getWindowToken(), 0);

					return true;
				}
				return false;
			}
		});

		return view;

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onPerformDefaultAction() {
		// This is called if the host menu item placed in the overflow menu of
		// the
		// action bar is clicked and the host activity did not handle the click.
		return true;
	}
}